class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def longestConsecutive(self, root: TreeNode) -> int:
        def dfs(node, parent_value, current_length):
            if not node:
                return current_length

            # 如果当前节点的值与父节点的值连续，则增加当前路径长度
            if node.val == parent_value + 1:
                current_length += 1
            else:
                current_length = 1  # 重置为1，因为当前节点不是连续的

            # 递归遍历左右子树
            left_length = dfs(node.left, node.val, current_length)
            right_length = dfs(node.right, node.val, current_length)

            # 返回左右子树中的最大值
            return max(current_length, left_length, right_length)

        # 辅助初始化
        return dfs(root, root.val - 1, 0)
